package com.xuecheng.test.rabbitmq;

import com.rabbitmq.client.*;

import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.util.concurrent.TimeoutException;

/**
 * 接收路由奇数的类
 */
public class Consumer3_Routing_Email {
    // EMAIL队列
    private static final String QUEUE_INFORM_EMAIL = "queue_inform_email";
    // 交换机
    private static final String EXCHANGE_ROUTING_INFORM = "exchange_routing_inform";
    // 交换机key
    public static final String ROUTING_KEY_EMAIL = "email";

    public static void main(String[] args) {
        // 通过链接工程创建链接
        ConnectionFactory connectionFactory = new ConnectionFactory();
        connectionFactory.setHost("127.0.0.1");
        connectionFactory.setPort(5672);
        connectionFactory.setUsername("guest");
        connectionFactory.setPassword("guest");
        connectionFactory.setVirtualHost("/");
        Connection connection = null;
        try {
            // 创建链接
            connection = connectionFactory.newConnection();
            // 创建通道
            Channel channel = connection.createChannel();
            // 设置目的地
            channel.queueDeclare(QUEUE_INFORM_EMAIL,true,false,false,null);
            // 设置交换机
            /**
             * exchange: 交换机的名字
             * type: 交换机的类型
             *  FANOUT : 对应publish/subscribe工作模式
             *  DIRECT : 对应Routing工作模式
             *  TOPIC : 对应Topic工作模式
             *  HEADERS : 对应headers工作模式
             */
            channel.exchangeDeclare(QUEUE_INFORM_EMAIL, BuiltinExchangeType.DIRECT);
            // 绑定交换机
            channel.queueBind(QUEUE_INFORM_EMAIL,EXCHANGE_ROUTING_INFORM,ROUTING_KEY_EMAIL);
            // 接收消息
            channel.basicConsume(QUEUE_INFORM_EMAIL,true,new DefaultConsumer(channel){
                @Override
                public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties, byte[] body) throws IOException {
                    System.out.println("收到的消息为" + new String(body, StandardCharsets.UTF_8));
                }
            });
        } catch (TimeoutException | IOException e) {
            e.printStackTrace();
        }
    }
}
